<template>
    <div class="source-market">
      <!-- 顶部横幅 -->
      <div class="hero-banner">
        <div class="banner-content">
          <h1 class="banner-title">免费源码</h1>
          <p class="banner-subtitle">高质量源码分享平台，助力开发者快速实现项目</p>
          </div>
        </div>
        
      <!-- 筛选导航 -->
      <div class="filter-container">
        <div class="filter-tabs">
          <el-menu :default-active="activeFilter" mode="horizontal" @select="handleFilterChange">
            <el-menu-item index="all">
              <i class="el-icon-menu"></i>全部
            </el-menu-item>
            <el-menu-item index="free">
              <i class="el-icon-s-goods"></i>免费
            </el-menu-item>
            <el-menu-item index="paid">
              <i class="el-icon-s-finance"></i>付费
            </el-menu-item>
            <el-menu-item index="vip-free">
              <i class="el-icon-s-custom"></i>会员免费
            </el-menu-item>
            <el-menu-item index="vip-discount">
              <i class="el-icon-s-promotion"></i>会员折扣
            </el-menu-item>
            <el-menu-item index="lifetime">
              <i class="el-icon-s-flag"></i>永久会员免费
            </el-menu-item>
          </el-menu>
            </div>
            
        <!-- 排序按钮组 -->
        <div class="sort-controls">
          <el-dropdown @command="handleSortChange" trigger="click">
            <el-button type="primary" size="small">
              {{ getSortName(currentSort) }} <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="latest">
                <i class="el-icon-time"></i> 最新发布
              </el-dropdown-item>
              <el-dropdown-item command="hot">
                <i class="el-icon-star-on"></i> 人气最高
              </el-dropdown-item>
              <el-dropdown-item command="update">
                <i class="el-icon-refresh"></i> 最近更新
              </el-dropdown-item>
              <el-dropdown-item command="comment">
                <i class="el-icon-chat-dot-round"></i> 评论最多
              </el-dropdown-item>
              <el-dropdown-item command="download">
                <i class="el-icon-download"></i> 下载最多
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
              </div>
            </div>
            
      <!-- 项目列表 -->
      <div class="project-list" v-loading="loading">
        <el-row :gutter="24">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="project in projects" :key="project.id" class="project-col">
            <div class="project-card" @click="viewProject(project.id)">
              <div class="project-image">
                <img referrerpolicy="no-referrer" :src="project.coverImage || defaultProjectImage" :alt="project.name" class="card-image" >
                <div class="project-badge" v-if="project.isFree">免费源码</div>
                <div class="project-badge vip" v-else-if="project.isVipFree">会员免费</div>
                <div class="project-badge paid" v-else>付费</div>
            </div>
              <div class="project-details">
                <h3 class="project-title">{{ project.name }}</h3>
                <p class="project-description">{{ project.description }}</p>
                <div class="project-meta">
                  <div class="author">
                    <img :src="project.creatorAvatar || defaultAvatarImage" class="author-avatar">
                    
                    <span class="meta-date">{{ formatDate(project.createdTime) }}</span>
            </div>
                  <div class="price">
                    <span v-if="project.isFree" class="free-tag">免费</span>
                    <span v-else-if="project.isVipFree" class="vip-tag">会员免费</span>
                    <span v-else class="paid-tag">¥{{ project.price }}</span>
                </div>
                    </div>
                <div class="project-stats">
                  <div class="stat-item">
                    <i class="el-icon-download"></i>
                    <span>{{ project.downloadCount || 0 }}</span>
                  </div>
                  <div class="stat-item">
                    <i class="el-icon-view"></i>
                    <span>{{ project.viewCount || 0 }}</span>
                </div>
                  <div class="stat-item">
                    <i class="el-icon-chat-dot-round"></i>
                    <span>{{ project.commentCount || 0 }}</span>
                </div>
              </div>
            </div>
          </div>
          </el-col>
        </el-row>
  
        <!-- 无数据提示 -->
        <div class="empty-state" v-if="!loading && projects.length === 0">
          <i class="el-icon-folder-checked"></i>
          <p>暂无符合条件的项目，请尝试其他筛选条件</p>
              </div>
              </div>
              
      <!-- 分页控件 -->
      <div class="pagination-container" v-if="!loading && projects.length > 0">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page.sync="currentPage"
          @current-change="handlePageChange">
        </el-pagination>
              </div>
              
      <!-- 版权声明弹窗 -->
      <el-dialog
        title="重要提示"
        :visible.sync="copyrightDialogVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
        width="500px"
        center
        custom-class="copyright-dialog">
        <div class="copyright-content">
          <div class="dialog-icon">
            <i class="el-icon-warning-outline"></i>
              </div>
          <h2 class="dialog-title">版权与使用说明</h2>
          <div class="dialog-text">
            <p>欢迎使用ETNOR源码平台！为了保障作者权益和提供更好的服务体验，请遵循以下规则：</p>
            <ol>
              <li>本平台所有项目均享有版权保护，请通过合法渠道获取</li>
              <li>严禁使用爬虫、自动化工具等手段批量获取本站资源</li>
              <li>下载的源码仅供学习研究，请勿用于商业用途</li>
              <li>尊重作者劳动成果，共建良好开发社区</li>
            </ol>
            </div>
          <div class="agreement-checkbox">
            <el-checkbox v-model="agreementAccepted">我已阅读并同意上述条款</el-checkbox>
                  </div>
                </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" :disabled="!agreementAccepted" @click="acceptCopyright">我同意</el-button>
              </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  import devtools from 'devtools-detect';
  import detectDevtools from 'detect-devtools';
  
  export default {
    name: 'SourceMarket',
    data() {
      return {
        loading: false,
        projects: [],
        activeFilter: 'all',
        currentSort: 'latest',
        currentPage: 1,
        pageSize: 12,
        total: 0,
        defaultProjectImage: 'https://img.alicdn.com/imgextra/i4/O1CN01VBU6Ds1pHpnIk4QIV_!!6000000005332-0-tps-1432-804.jpg',
        defaultAvatarImage: 'https://img.alicdn.com/imgextra/i1/O1CN01EI83zy1vwbvu7z1Ks_!!6000000006240-0-tps-200-200.jpg',
        // 版权弹窗相关
        copyrightDialogVisible: false,
        agreementAccepted: false,
        watermarkText: 'ETNOR源码 - 请勿非法使用',
        devtoolsCheckInterval: null
      }
    },
    computed: {
      filterParams() {
        // 根据选择的筛选条件返回请求参数
        const params = {};
        
        switch(this.activeFilter) {
          case 'free':
            params.isFree = true;
            break;
          case 'paid':
            params.isFree = false;
            break;
          case 'vip-free':
            params.isVipFree = true;
            break;
          case 'vip-discount':
            params.vipDiscount = true;
            break;
          case 'lifetime':
            params.isLifetimeVipFree = true;
            break;
          default:
            // 全部，不传额外参数
            break;
        }
        
        return params;
      }
    },
    created() {
      // 检查是否首次访问
      this.checkFirstVisit();
      
      // 添加防调试
      this.setupDevToolsDetection();
      
      // 添加页面水印
      this.addWatermark();
      
      // 禁止右键和复制
      this.disableRightClickAndCopy();
      
      // 初始检测
      if (devtools.isOpen) {
        this.handleDevToolsOpen();
      }
      
      // 监听状态变化
      window.addEventListener('devtoolschange', event => {
        if (event.detail.isOpen) {
          this.handleDevToolsOpen();
        }
      });
    },
    mounted() {
      // 防止控制台调试
      this.preventConsoleDebug();
      
      // 页面加载完成后获取项目
      if (localStorage.getItem('copyright_agreed') === 'true') {
        this.fetchProjects();
      }
    },
    methods: {
      // 检查是否首次访问
      checkFirstVisit() {
        if (localStorage.getItem('copyright_agreed') !== 'true') {
          this.copyrightDialogVisible = true;
        }
      },
      
      // 接受版权协议
      acceptCopyright() {
        localStorage.setItem('copyright_agreed', 'true');
        this.copyrightDialogVisible = false;
        this.fetchProjects();
      },
      
      // 添加防调试
      setupDevToolsDetection() {
        detectDevtools({
          // 检测到开发者工具时回调
          whenOpened: () => {
            // 保存当前URL
            sessionStorage.setItem('source_page_url', window.location.href);
            // 重定向到警告页面
            window.location.href = '/warning';
          }
        });
      },
      
      // 添加页面水印
      addWatermark() {
        const watermark = document.createElement('div');
        watermark.className = 'watermark';
        watermark.style.position = 'fixed';
        watermark.style.top = '0';
        watermark.style.left = '0';
        watermark.style.width = '100%';
        watermark.style.height = '100%';
        watermark.style.pointerEvents = 'none';
        watermark.style.zIndex = '9999';
        
        // 创建更淡的水印
        const canvas = document.createElement('canvas');
        canvas.width = 400;
        canvas.height = 300;
        const ctx = canvas.getContext('2d');
        ctx.font = '14px Arial';
        ctx.fillStyle = 'rgba(0, 0, 0, 0.05)'; // 更淡的水印
        ctx.rotate(-15 * Math.PI / 180);
        for (let i = -canvas.width; i < canvas.width * 2; i += 200) {
          for (let j = -canvas.height; j < canvas.height * 2; j += 120) {
            ctx.fillText(this.watermarkText, i, j);
          }
        }
        
        watermark.style.backgroundImage = `url(${canvas.toDataURL()})`;
        document.body.appendChild(watermark);
        
        // 保护水印不被删除，但减少检查频率
        setInterval(() => {
          if (!document.querySelector('.watermark')) {
            document.body.appendChild(watermark);
          }
        }, 2000);
      },
      
      // 禁止右键和复制
      disableRightClickAndCopy() {
        // 仅针对项目内容区域禁用右键
        document.querySelector('.project-list').addEventListener('contextmenu', event => {
          event.preventDefault();
          this.$message.warning('为保护作者权益，请勿尝试复制内容');
        });
        
        // 允许用户选择文本，但提示不要复制
        document.querySelector('.project-list').addEventListener('copy', event => {
          event.preventDefault();
          this.$message.warning('为保护作者权益，请勿复制内容');
        });
      },
      
      // 防止控制台调试
      preventConsoleDebug() {
        // 重写控制台方法
        const methods = ['log', 'debug', 'info', 'warn', 'error'];
        const consoleBackup = {};
        
        methods.forEach(method => {
          consoleBackup[method] = console[method];
          console[method] = function() {
            const stackInfo = new Error().stack.split('\n')[2];
            if (stackInfo.includes('from devtools')) {
              alert('检测到使用控制台调试，系统将自动退出！');
              window.location.href = '/';
          return;
        }
            consoleBackup[method].apply(console, arguments);
          };
        });
      },
      
      // 获取项目列表
      async fetchProjects() {
        this.loading = true;
        
        try {
          // 构建请求参数
          const params = {
            page: this.currentPage,
            size: this.pageSize,
            sortBy: this.currentSort,
            ...this.filterParams
          };
          
          // 发送请求
          const response = await axios.get('/api/projects', { params });
          
          if (response.data.code === 200) {
            this.projects = response.data.data;
            // 设置总数
            this.total = response.data.total || this.projects.length * 5;
          } else {
            this.$message.error(response.data.message || '获取项目列表失败');
          }
        } catch (error) {
          console.error('获取项目列表失败:', error);
          this.$message.error('获取项目列表失败，请稍后重试');
        } finally {
          this.loading = false;
        }
      },
      
      // 处理筛选变化
      handleFilterChange(index) {
        this.activeFilter = index;
        this.currentPage = 1; // 重置页码
        this.fetchProjects();
      },
      
      // 处理排序变化
      handleSortChange(command) {
        this.currentSort = command;
        this.fetchProjects();
      },
      
      // 处理页码变化
      handlePageChange(page) {
        this.currentPage = page;
        this.fetchProjects();
      },
      
      // 查看项目详情
      viewProject(id) {
        // 跳转到项目详情页面
        this.$router.push(`/project/${id}`);
      },
      
      // 获取排序名称
      getSortName(sortType) {
        const map = {
          'latest': '最新发布',
          'hot': '人气最高',
          'update': '最近更新',
          'comment': '评论最多',
          'download': '下载最多'
        };
        return map[sortType] || '最新发布';
      },
      
      // 格式化日期
      formatDate(dateString) {
        if (!dateString) return '未知日期';
        
      const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        
        return `${year}-${month}-${day}`;
      },
      
      handleDevToolsOpen() {
        alert('检测到开发者工具已打开，为保护网站资源，部分功能将被限制');
        // 可以在这里添加其他反应措施
      }
    },
    beforeDestroy() {
      // 移除水印
      const watermark = document.querySelector('.watermark');
      if (watermark) {
        document.body.removeChild(watermark);
    }
  }
}
</script>

<style scoped>
  .source-market {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

  /* 顶部横幅样式 */
  .hero-banner {
    position: relative;
    border-radius: 10px;
    background-image: linear-gradient(135deg, #5b51d8 0%, #833ab4 50%, #fd1d1d 100%);
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 30px;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  }
  
  .hero-banner::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: url('');
    opacity: 0.3;
  }
  
  .banner-content {
    text-align: center;
    z-index: 1;
  color: white;
  }
  
  .banner-title {
    font-size: 42px;
    font-weight: 700;
    margin: 0 0 10px;
    letter-spacing: 2px;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }
  
  .banner-subtitle {
    font-size: 18px;
    margin: 0;
    opacity: 0.9;
    max-width: 600px;
  }
  
  /* 筛选导航样式 */
  .filter-container {
    margin-bottom: 30px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  display: flex;
    justify-content: space-between;
  align-items: center;
    padding: 0 15px 0 0; /* 右侧留空间给排序按钮 */
  }
  
  .filter-tabs {
    flex: 1;
  }
  
  /* 覆盖 Element UI 菜单样式 */
  .filter-tabs >>> .el-menu {
    border-bottom: none;
  }
  
  .filter-tabs >>> .el-menu-item {
    font-size: 15px;
    height: 55px;
    line-height: 55px;
  }
  
  .filter-tabs >>> .el-menu-item.is-active {
    font-weight: 600;
  }
  
  .filter-tabs >>> .el-menu-item i {
    margin-right: 5px;
  }
  
  .sort-controls {
    margin-left: 15px;
  }
  
  /* 项目列表样式 */
  .project-list {
    min-height: 400px; /* 确保加载时有足够高度 */
  }
  
  .project-col {
  margin-bottom: 30px;
  }
  
  .project-card {
    height: 100%;
    border-radius: 8px;
    overflow: hidden;
    background: white;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    cursor: pointer;
    display: flex;
    flex-direction: column;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }
  
  .project-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  }
  
  .project-image {
    position: relative;
    height: 180px;
    overflow: hidden;
  }
  
  .card-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
  }
  
  .project-card:hover .card-image {
    transform: scale(1.05);
  }
  
  .project-badge {
    position: absolute;
    top: 12px;
    left: 12px;
    background-color: #67c23a;
    color: white;
    padding: 4px 10px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
    letter-spacing: 0.5px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
  }
  
  .project-badge.vip {
    background-color: #e6a23c;
  }
  
  .project-badge.paid {
    background-color: #f56c6c;
  }
  
  .project-details {
    padding: 16px;
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  
  .project-title {
    margin: 0 0 10px;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .project-description {
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 15px;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    flex: 1;
  }
  
  .project-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    border-top: 1px solid #f0f2f5;
    padding-top: 12px;
  }
  
  .author {
  display: flex;
  align-items: center;
  }
  
  .author-avatar {
    width: 24px;
    height: 24px;
  border-radius: 50%;
    margin-right: 8px;
    border: 1px solid #f0f2f5;
  }
  
  .meta-date {
    color: #909399;
  font-size: 12px;
}

  .price .free-tag {
    color: #67c23a;
    font-weight: 600;
    font-size: 14px;
  }
  
  .price .vip-tag {
    color: #e6a23c;
    font-weight: 600;
    font-size: 14px;
  }
  
  .price .paid-tag {
    color: #f56c6c;
    font-weight: 600;
    font-size: 14px;
  }
  
  .project-stats {
  display: flex;
    justify-content: space-between;
  }
  
  .stat-item {
    color: #909399;
    font-size: 12px;
    display: flex;
    align-items: center;
  }
  
  .stat-item i {
    margin-right: 4px;
    font-size: 14px;
  }
  
  /* 空状态样式 */
  .empty-state {
    text-align: center;
    padding: 60px 0;
    color: #909399;
  }
  
  .empty-state i {
    font-size: 60px;
    margin-bottom: 20px;
    opacity: 0.5;
  }
  
  .empty-state p {
  font-size: 16px;
}

  /* 分页样式 */
  .pagination-container {
  text-align: center;
    margin: 20px 0 40px;
  }
  
  /* 版权弹窗样式 */
  .copyright-dialog >>> .el-dialog__header {
    padding: 0;
    height: 8px;
    background: linear-gradient(90deg, #3f51b5, #9c27b0, #e91e63, #ff5722);
  }
  
  .copyright-dialog >>> .el-dialog__title,
  .copyright-dialog >>> .el-dialog__headerbtn {
    display: none;
  }
  
  .copyright-dialog >>> .el-dialog__body {
    padding: 30px 20px 20px;
  }
  
  .copyright-content {
    text-align: center;
  }
  
  .dialog-icon {
    font-size: 60px;
    color: #e6a23c;
    margin-bottom: 20px;
  }
  
  .dialog-title {
    color: #303133;
    font-size: 24px;
    margin-bottom: 20px;
  }
  
  .dialog-text {
    text-align: left;
    color: #606266;
    line-height: 1.8;
    margin-bottom: 25px;
  }
  
  .dialog-text p {
    margin-bottom: 15px;
  }
  
  .dialog-text ol {
    padding-left: 20px;
  }
  
  .dialog-text li {
    margin-bottom: 10px;
  }
  
  .agreement-checkbox {
    margin: 20px 0;
    text-align: left;
  }
  
  .copyright-dialog >>> .el-dialog__footer {
    padding: 10px 20px 25px;
    text-align: center;
  }
  
  .copyright-dialog >>> .el-button--primary {
    width: 180px;
    height: 45px;
    border-radius: 25px;
    font-size: 16px;
    background: linear-gradient(90deg, #3f51b5, #9c27b0);
    border: none;
  transition: all 0.3s ease;
}

  .copyright-dialog >>> .el-button--primary:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 7px 14px rgba(50, 50, 93, 0.1), 0 3px 6px rgba(0, 0, 0, 0.08);
    background: linear-gradient(90deg, #5c6bc0, #ab47bc);
  }
  
  .copyright-dialog >>> .el-button--primary:disabled {
    background: #ccc;
    opacity: 0.7;
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .hero-banner {
      height: 160px;
    }
    
    .banner-title {
      font-size: 32px;
    }
    
    .banner-subtitle {
  font-size: 14px;
    }
    
    .filter-container {
      flex-direction: column;
      padding: 0;
    }
    
    .filter-tabs {
      width: 100%;
      overflow-x: auto;
    }
    
    .sort-controls {
      margin: 0 0 15px 0;
      width: 100%;
      display: flex;
      justify-content: center;
      padding: 10px 0;
    }
    
    .project-image {
      height: 150px;
    }
  }
  </style>
  
  <style>
  /* 全局样式，确保水印等能够正常工作 */
  html {
    -webkit-user-select: text;
    -moz-user-select: text;
    -ms-user-select: text;
    user-select: text;
  }
  body {
  /* 防止开发者工具破坏布局 */
  min-height: 100vh;
  overflow-y: auto;
  position: relative;
}

/* 添加页面复制保护 */
::selection {
  background: rgba(91, 81, 216, 0.2);
  color: inherit;
}

::-moz-selection {
  background: rgba(91, 81, 216, 0.2);
  color: inherit;
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.copyright-dialog >>> .el-dialog {
  animation: fadeIn 0.5s ease-out;
  border-radius: 8px;
  overflow: hidden;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(180deg, #5b51d8, #833ab4);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(180deg, #4a41b8, #6d309b);
}
  
